/**
 * tree 转 list
 * key 一般为 children
 */
function treeToFlat(treeList, key) {
    let flatList = []

    function toFlat(treeList, key) {
        if (flatList.length > 9999) {
            return
        }
        treeList.map(e => {
            let children = e[key]
            delete e[key]
            flatList.push(e)
            // 递归：有条件的自己调用自己，条件是 e.children.length 为真
            if (children && children.length) {
                toFlat(children, flatList)
            }
        })
    }

    toFlat(treeList, key)
    return flatList
}

/**
 * list 转 tree
 * id 为主键id
 * pid为父id
 * key 一般为 children
 */
function flatToTree(flatList, id, pid, key) {
    let menuObj = {}
    function tree(flatList, parentId) {
        flatList.forEach(item => {
            item[key] = []
            menuObj[item[id]] = item
        })
        return flatList.filter(item => {
            if (item[pid] !== parentId) {
                menuObj[item[pid]][key].push(item)
                return false
            }
            return true
        })
    }

    return tree(flatList, 0)
}


export default {
    treeToFlat, flatToTree
}